﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using Betarium.PotonEditor.Properties;

namespace Betarium.PotonEditor
{
	public partial class MainForm : Form
	{
		#region protected member
		protected PaletteForm m_ColorForm = new PaletteForm();
		#endregion

		public PaletteForm ColorPalette
		{
			get { return m_ColorForm; }
			set { m_ColorForm = value; }
		}

		public MainForm()
		{
			InitializeComponent();
			statusStrip.Items[0].Text = "";
			statusStrip.Items[1].Text = "";
			statusStrip.Items[2].Text = "";
			editMenu.Enabled = false;
		}

		public void SetStatus(int nState, string str)
		{
			statusStrip.Items[nState].Text = str;
		}

		private void OnLoad(object sender, EventArgs e)
		{
			statusStrip.Items[0].Text = "";
			statusStrip.Items[1].Text = "";
			Icon = Resources.Poton;
#if DEBUG
			Text = Text + "(デバッグ)";
#endif

			menuViewShowPalette.Checked = Settings.Default.ShowColorPalette;
			statusStrip.Visible = Settings.Default.ShowStatusBar;
			toolStrip.Visible = Settings.Default.ShowToolBar;
			menuViewToolBar.Checked = Settings.Default.ShowToolBar;
			menuViewStatusBar.Checked = Settings.Default.ShowStatusBar;

			Point posColor = PointToScreen(new Point(0, ClientSize.Height - m_ColorForm.Height));
			m_ColorForm.Location = posColor;
			if (Settings.Default.ShowColorPalette)
			{
				m_ColorForm.Show(this);
			}

			string[] aCommand = Environment.GetCommandLineArgs();
			for (int nLoop = 1; nLoop < aCommand.Length; nLoop++)
			{
				if (!File.Exists(aCommand[nLoop]))
					continue;
				EditViewForm view = new EditViewForm();
				view.LoadFile(this, aCommand[nLoop]);
			}
			if (this.MdiChildren.Length == 0)
			{
				EditViewForm view = new EditViewForm();
                view.CreateFromSize(this, Settings.Default.NewImageWidth, Settings.Default.NewImageHeight);
			}

		}

		public void AddLatestFile(string sPath)
		{
			string[] aBeforeList = GetLatestList();
			List<string> aPathList = new List<string>();
			foreach (string sItemPath in aBeforeList)
			{
				if (sItemPath.Equals(sPath, StringComparison.OrdinalIgnoreCase))
					continue;
				aPathList.Add(sItemPath);
			}
			aPathList.Insert(0, sPath);
			while (aPathList.Count > 10)
			{
				aPathList.RemoveAt(aPathList.Count - 1);
			}
			string sResult = "";
			foreach (string sItemPath in aPathList)
			{
				sResult += sItemPath + ";";
			}
			Settings.Default.LatestFileList = sResult;
		}
		public void RemoveLatestFile(string sPath)
		{
			string[] aBeforeList = GetLatestList();
			List<string> aPathList = new List<string>();
			foreach (string sItemPath in aBeforeList)
			{
				if (sItemPath.Equals(sPath, StringComparison.OrdinalIgnoreCase))
					continue;
				aPathList.Add(sItemPath);
			}
			while (aPathList.Count > 10)
			{
				aPathList.RemoveAt(aPathList.Count - 1);
			}
			string sResult = "";
			foreach (string sItemPath in aPathList)
			{
				sResult += sItemPath + ";";
			}
			Settings.Default.LatestFileList = sResult;
		}

		/// <summary>
		/// ファイルをロードしビューとして表示する。
		/// </summary>
		/// <param name="sPath"></param>
		public EditViewForm LoadFile(string sPath)
		{
			if (!File.Exists(sPath))
			{
				RemoveLatestFile(sPath);
				string sMessage = String.Format("ファイルが存在しません。\n[{0}]", sPath);
				Utility.Message(sMessage);
				return null;
			}
			EditViewForm view = new EditViewForm();
			view.LoadFile(this, sPath);
			AddLatestFile(sPath);
			return view;
		}

		public void ShowFullScreen(Bitmap image)
		{
			FullScrForm form = new FullScrForm();
			form.Image = Utility.CloneImage(image);
//			form.Size = Screen.PrimaryScreen.Bounds.Size;
			form.Show();
		}

		public void ShowFullScreen(string sPath)
		{
			if (!File.Exists(sPath))
			{
				string sMessage = String.Format("ファイルが存在しません。\n[{0}]", sPath);
				Utility.Message(sMessage);
				return;
			}
			Bitmap newImage = null;
			using (FileStream stream = new FileStream(sPath, FileMode.Open, FileAccess.Read))
			{
				newImage = Utility.LoadImage(stream);
//				newImage = new Bitmap(stream);
			}
			FullScrForm form = new FullScrForm();
			form.Image = newImage;
			form.Show();
		}

		private void OnDragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				e.Effect = DragDropEffects.All;
			}
		}

		private void OnDragDrop(object sender, DragEventArgs e)
		{
			string[] aPath = (string[])e.Data.GetData(DataFormats.FileDrop, false);

			this.Activate();
			if (aPath.Length == 1 && Directory.Exists(aPath[0]))
			{
				ListViewForm form = new ListViewForm();
				form.TargetFolder = aPath[0];
				if (ActiveMdiChild == null || ActiveMdiChild.WindowState == FormWindowState.Maximized)
				{
					form.WindowState = FormWindowState.Maximized;
				}
				form.MdiParent = this;
				form.Show();
				return;
			}
			Array.Sort(aPath);
			try
			{
				foreach (string sPath in aPath)
				{
					LoadFile(sPath);
				}
			}
			catch (UserException ue)
			{
				Utility.ReportException(ue);
			}
		}

		//////////
		#region menus
		public void menuFileNew_Click(object sender, EventArgs e)
		{
			EditViewForm view = new EditViewForm();
			view.MdiParent = this;
//			view.CreateFromSize(this, 640, 480);
			view.CreateFromSize(this, Settings.Default.NewImageWidth, Settings.Default.NewImageHeight);
			int nCount = this.MdiChildren.Length;
			System.Diagnostics.Debug.WriteLine("cnt=" + nCount);
		}

		public void menuFileOpen_Click(object sender, EventArgs e)
		{
			string sFileName = "";
			if (!Utility.QueryOpenImage(ref sFileName))
				return;

			LoadFile(sFileName);
		}

		private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		public void menuViewToolBar_Click(object sender, EventArgs e)
		{
			toolStrip.Visible = menuViewToolBar.Checked;
		}

		public void menuViewStatusbar_Click(object sender, EventArgs e)
		{
			statusStrip.Visible = menuViewStatusBar.Checked;
		}

		private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.Cascade);
		}

		private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.TileVertical);
		}

		private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.TileHorizontal);
		}

		private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			LayoutMdi(MdiLayout.ArrangeIcons);
		}

		private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			foreach (Form childForm in MdiChildren)
			{
				childForm.Close();
			}
		}

		public void menuFileNewClip_Click(object sender, EventArgs e)
		{
			if (!Clipboard.ContainsImage())
			{
				return;
			}
			Bitmap image = Utility.GetClipbardImage();
			EditViewForm view = new EditViewForm();
			view.CreateFromImage(this, image);
		}

		#endregion

		private void MainForm_MdiChildActivate(object sender, EventArgs e)
		{
			if (ActiveMdiChild == null)
			{
				SetStatus(0, "");
				SetStatus(1, "");
				SetStatus(2, "");
				return;
			}
			if (ActiveMdiChild is EditViewForm)
			{
				EditViewForm view = (EditViewForm)ActiveMdiChild;
				view.UpdateStatusText();
			}
		}

		public string[] GetLatestList()
		{
			string sLatest = Settings.Default.LatestFileList;
			string[] aPath = sLatest.Split(new char[] { ';' });
			List<string> aPathList = new List<string>();
			foreach (string sItemPath in aPath)
			{
				if (sItemPath.Length == 0)
					continue;
				aPathList.Add(sItemPath);
			}
			return aPathList.ToArray();
		}

		public void UpdateMenu()
		{
			menuFileLatestMenu.DropDownItems.Clear();

			string[] aPathList = GetLatestList();
			foreach (string sItemPath in aPathList)
			{
				ToolStripMenuItem item = new ToolStripMenuItem(Path.GetFileName(sItemPath), null, menuFileLatest_Click);
				item.ToolTipText = sItemPath;
				menuFileLatestMenu.DropDownItems.Add(item);
			}
			menuFileLatestMenu.Enabled = (aPathList.Length > 0);
		}

		private void menuStrip_MenuActivate(object sender, EventArgs e)
		{
			UpdateMenu();
		}

		private void menuFileLatest_Click(object sender, EventArgs e)
		{
			ToolStripMenuItem menu = (ToolStripMenuItem)sender;
			LoadFile(menu.ToolTipText);
		}

		private void menuHelpAbout_Click(object sender, EventArgs e)
		{
			string sVertion = Application.ProductName + " Ver " + Application.ProductVersion + "\n";
			sVertion += "Copyright (C) 2008-2010 Beta.Ito";
			Utility.Message(sVertion);
		}

		private void toolNewFromClip_Click(object sender, EventArgs e)
		{
			if (!Clipboard.ContainsImage())
			{
				return;
			}
			Bitmap image = Utility.GetClipbardImage();
			EditViewForm view = new EditViewForm();
			view.CreateFromImage(this, image);
		}

		private void toolPaintSelect_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Select);
		}

		private void toolPaintPen_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Pen);
		}

		private void toolPaintRect_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Rect);
		}

		private void toolPaintLine_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Line);
		}

		private void toolViewZoomNone_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.menuViewNormalRate_Click(sender, e);
		}

		private void toolViewZoomOut_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.menuViewRateReduce_Click(sender, e);
		}

		private void toolViewZoomIn_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.menuViewRateEnlarge_Click(sender, e);
		}

		private void menuViewShowPalette_Click(object sender, EventArgs e)
		{
			if (m_ColorForm.Visible)
			{
				m_ColorForm.Hide();
			}
			else
			{
				m_ColorForm.Show(this);
			}
			menuViewShowPalette.Checked = m_ColorForm.Visible;
		}

		private void toolViewRate_TextUpdate(object sender, EventArgs e)
		{
		}

		private void toolViewRate_TextChanged(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetViewRate(Int32.Parse(toolViewRate.Text));
			view.Activate();

		}

		private void toolPaintErase_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Erase);
		}

		private void toolFull_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			ShowFullScreen(view.Image);
			/*
			MdiParent.ShowFu.Show
			FullScrForm form = new FullScrForm();
			form.Image = view.Image;
			form.Show();
			*/
		}

		private void OnFormClosed(object sender, FormClosedEventArgs e)
		{
			Settings.Default.ShowColorPalette = m_ColorForm.Visible;
			Settings.Default.ShowStatusBar = statusStrip.Visible;
			Settings.Default.ShowToolBar = toolStrip.Visible;
			m_ColorForm.Dispose();
		}

		private void menuToolSpuit_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Spuit);
		}

		private void menuToolCircle_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.SetPainter(EditViewForm.ToolType.Circle);
		}

		private void menuDrawFillOuter_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.PaintState.FillMode = PaintInfo.FillModes.Outer;
		}

		private void menuDrawFillBoth_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.PaintState.FillMode = PaintInfo.FillModes.Both;
		}

		private void menuDrawFillInner_Click(object sender, EventArgs e)
		{
			if (!(ActiveMdiChild is EditViewForm))
				return;
			EditViewForm view = (EditViewForm)ActiveMdiChild;
			view.PaintState.FillMode = PaintInfo.FillModes.Inner;
		}

        private void menuToolText_Click(object sender, EventArgs e)
        {
            if (!(ActiveMdiChild is EditViewForm))
                return;
            EditViewForm view = (EditViewForm)ActiveMdiChild;
            view.SetPainter(EditViewForm.ToolType.Text);
        }

        private void menuStrip_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void menuStrip_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void menuStrip_KeyUp(object sender, KeyEventArgs e)
        {

        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {

        }
        protected override bool ProcessDialogKey(Keys keyData)
        {
            return false;
        }
	}
}
